package com.jshcbd.mvp_kt_demo.base.fragment

import android.app.Activity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.viewbinding.ViewBinding
import com.dylanc.viewbinding.base.inflateBindingWithGeneric
import com.trello.rxlifecycle2.components.support.RxFragment

abstract class BaseLazyFragment<VB : ViewBinding> : RxFragment() {
    var binding: VB? = null
    private val _binding: VB get() = binding!!
    private var mRootView: View? = null
    var mActivity: Activity? = null

    //是否第一次加载
    private var isFirstLoad = false
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mActivity = activity
        if (mRootView == null) {
            binding = this.inflateBindingWithGeneric(layoutInflater, container, false)
            mRootView = _binding.root
            init()
        }
        val parent = mRootView!!.parent as ViewGroup
        parent.removeView(mRootView)
        //视图创建完成，将变量置为true
        isFirstLoad = true
        return mRootView
    }

    override fun onResume() {
        super.onResume()
        //        //视图变为可见并且是第一次加载
        if (isFirstLoad) {
            onLazyLoad()
            isFirstLoad = false
        }
    }

    protected abstract fun onLazyLoad()
    protected abstract fun init()
    override fun onDestroy() {
        super.onDestroy()
        //视图销毁将变量置为false
        isFirstLoad = false
    }

    override fun onDestroyView() {
        super.onDestroyView()
        binding = null
        isFirstLoad = false
    }
}